const express = require("express");
const app = express();
const router = express.Router();

const { mysql, executeQuery } = require("../../mysql");

router.post("/create-teacher", async (req, res) => {
  try {
    const { id, name, sex, tel, subject, activeClass, grade, is_class_teacher, major } = req.body;

    console.log(id, name, sex, tel, subject, activeClass, grade, is_class_teacher, major);
    // 判断是否是班主任
    const isClassTeacher = is_class_teacher && is_class_teacher === true;

    let majorName = null;  //  科目

    // 如果是班主任，获取专业名称
    if (isClassTeacher) {

      majorName = await getMajorNameById(major);

    } else {

      // grade = '' ; //  年级

      // activeClass = '' ; // 班级

    }

    const hashedPassword = 'qwer1234'; // 实际需要替换为密码的散列值

    const sql = `
      INSERT INTO tb_teacher (id, password, name, sex, tel, subject, is_class_teacher, grade, class_name, major, major_id, created_at)
      VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)
    `;

    const insertParams = [id, hashedPassword, name, sex, tel, subject, isClassTeacher, grade, activeClass, majorName , major];

    const result = await executeQuery(sql, insertParams);

    if (result) {

      res.status(200).json({ 
        success: true,
        id: id 
      });

    } else {
      throw new Error('Failed to insert teacher data.');
    }
  } catch (error) {
    console.error('Error creating teacher:', error);
    res.status(500).send('Internal Server Error');
  }
});

async function getMajorNameById(majorId) {
  try {
    const sql = 'SELECT Major_Name FROM tb_major WHERE Major_ID = ?';
    const [rows] = await executeQuery(sql, [majorId]);

    if (rows ) {
      return rows.Major_Name; // 返回第一个匹配的 Major_Name
    } else {
      throw new Error(`Major with ID ${majorId} not found.`);
    }
  } catch (error) {
    console.error('Error fetching major name:', error);
    throw error;
  }
}

module.exports = router;
